package com.weng.cloud.service8881.hystrix;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Author: weng
 * @Date: 2022/3/11
 * @Description: com.weng.cloud.service8881.hystrix
 */
@RestController
public class RestTemplateController {

    @Bean
    @LoadBalanced
    private RestTemplate restTemplate(){
        //测试zuul retry,这里先注释请求工厂
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(1000);
        factory.setReadTimeout(1000);
//        factory.setConnectTimeout(8000);
//        factory.setReadTimeout(8000);
        return new RestTemplate(factory);
//        return new RestTemplate();
    }

    @Resource
    private RestTemplate restTemplate;

    /**
     * <br/>function:
     * <br/>tip: restTemplate + hystrix的注解配置方式 @see {@link https://www.cnblogs.com/duanxz/p/15708773.html}
     *
     * @param: []
     * @return: java.lang.String
     * @author: weng
     * @date: 2022/3/11 0:55
     */
    @GetMapping(value = "/testRestTemplate")
    @HystrixCommand(
        fallbackMethod = "doFallbackMethod",
        commandProperties = {
            //熔断超时设置？？
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000"),//指定多久超时，单位毫秒。超时进fallback
        }
    )
    public String testRestTemplate(){
        System.err.println("我是瓜皮");
        //此时直接熔断，并没有重试
        //int i = 1 / 0;
        String url = "http://weng-cloud-service-8882/testRestTemplate/";
        String result = this.restTemplate.getForObject(url, String.class);
        //先重试后熔断
        //int i = 1 / 0;
        return result;
    }

    private String doFallbackMethod(){
        return "是shit呀";
    }
}
